package cn.gson.vboot.interceptor;

import cn.gson.vboot.common.AcLog;
import cn.gson.vboot.model.pojo.User;
import cn.gson.vboot.service.AcLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2018 soho team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : cn.gson.vboot.interceptor</li>
 * <li>Version     : 1.0</li>
 * <li>Creation    : 2018年09月08日</li>
 * <li>@author     : ____′↘夏悸</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
@Component
@Slf4j
public class LogInterceptor extends HandlerInterceptorAdapter {

    ThreadLocal<AcLog> acLogThreadLocal = new ThreadLocal<>();
    ThreadLocal<HttpSession> sessionThreadLocal = new ThreadLocal<>();
    ThreadLocal<User> userThreadLocal = new ThreadLocal<>();

    @Autowired
    AcLogService acLogService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod hd = (HandlerMethod) handler;
            acLogThreadLocal.set(hd.getMethodAnnotation(AcLog.class));
            sessionThreadLocal.set(request.getSession());
            if (request.getSession() != null) {
                userThreadLocal.set((User) request.getSession().getAttribute("user"));
            }
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        try {
            AcLog acLog = acLogThreadLocal.get();
            if (acLog != null) {
                cn.gson.vboot.model.pojo.AcLog log = new cn.gson.vboot.model.pojo.AcLog();
                User user = userThreadLocal.get();
                if (user == null && sessionThreadLocal.get() != null) {
                    user = (User) sessionThreadLocal.get().getAttribute("user");
                }

                log.setModule(acLog.module());
                log.setIp(getIpAddr(request));

                if (acLog.params() != null && acLog.params().length > 0) {
                    StringBuffer sb = new StringBuffer("[");
                    for (int i = 0; i < acLog.params().length; i++) {
                        String key = acLog.params()[i];
                        String value = request.getParameter(key);
                        sb.append(key).append(":").append(value);
                        sb.append(",");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    sb.append("]");

                    log.setAction(acLog.action() + sb);
                } else {
                    log.setAction(acLog.action());
                }

                if (ex != null) {
                    log.setException(ex.getMessage());
                }

                if (user != null) {
                    log.setUid(user.getId());
                }

                acLogService.save(log);
            }
        } catch (Exception e) {
            log.error("日志记录异常", e);
        }
    }

    private String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}
